from PyQt5.QtCore import QElapsedTimer, QTimer
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLabel


class PauseableTimer:
    def __init__(self):
        self._elapsed_timer = QElapsedTimer()  # 内部使用 QElapsedTimer
        self._paused_time = 0  # 暂停时累计的时间（毫秒）
        self._is_running = False  # 是否正在运行

    def start(self):
        """
        开始计时，如果已暂停则继续
        """
        if not self._is_running:
            self._elapsed_timer.start()  # 启动底层计时器
            self._is_running = True

    def pause(self):
        """
        暂停计时，记录当前累计时间
        """
        if self._is_running:
            self._paused_time += self._elapsed_timer.elapsed()  # 累计已经运行的时间
            self._elapsed_timer.invalidate()  # 停止底层计时器
            self._is_running = False

    def reset(self):
        """
        重置计时器，清零所有状态
        """
        self._elapsed_timer.invalidate()
        self._paused_time = 0
        self._is_running = False

    def elapsed(self) -> int:
        """
        返回从开始到当前（或暂停时）的总时间（毫秒）
        """
        if self._is_running:
            return self._paused_time + self._elapsed_timer.elapsed()
        else:
            return self._paused_time


class TimerDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.timer = PauseableTimer()  # 使用我们自定义的可暂停计时器
        self.init_ui()

        # 用于更新界面显示的定时器（每100毫秒刷新一次）
        self.update_timer = QTimer(self)
        self.update_timer.timeout.connect(self.update_display)

    def init_ui(self):
        self.setWindowTitle('可暂停计时器 (PyQt5 + 组合模式)')
        self.layout = QVBoxLayout()

        self.label = QLabel("00:00:00.000", self)
        self.label.setStyleSheet("font-size: 24px;")
        self.layout.addWidget(self.label)

        self.start_button = QPushButton("开始", self)
        self.start_button.clicked.connect(self.on_start)
        self.layout.addWidget(self.start_button)

        self.pause_button = QPushButton("暂停", self)
        self.pause_button.clicked.connect(self.on_pause)
        self.layout.addWidget(self.pause_button)

        self.reset_button = QPushButton("重置", self)
        self.reset_button.clicked.connect(self.on_reset)
        self.layout.addWidget(self.reset_button)

        self.setLayout(self.layout)

    def on_start(self):
        self.timer.start()
        if not self.update_timer.isActive():
            self.update_timer.start(100)  # 每100毫秒更新一次显示

    def on_pause(self):
        self.timer.pause()
        if self.update_timer.isActive():
            self.update_timer.stop()

    def on_reset(self):
        self.timer.reset()
        self.update_display()  # 立即更新显示
        if self.update_timer.isActive():
            self.update_timer.stop()

    def update_display(self):
        elapsed_ms = self.timer.elapsed()
        # 将毫秒转换为时:分:秒.毫秒格式
        hours, remainder = divmod(elapsed_ms, 3600 * 1000)
        minutes, remainder = divmod(remainder, 60 * 1000)
        seconds, milliseconds = divmod(remainder, 1000)
        time_str = f"{int(hours):02}:{int(minutes):02}:{int(seconds):02}.{milliseconds:03}"
        self.label.setText(time_str)


if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    demo = TimerDemo()
    demo.show()
    sys.exit(app.exec_())